const { debug } = require("console");

const db = uniCloud.database();
const dbCmd = db.command;

exports.main = async (event, context) => {
    let {
        optType,
        param
    } = event;
    switch (optType) {
        case "getFavRes": {
            return getFavoritesResList(param.currentPage - 1, param.userId);
        }
        case "add": {
            return addFavorites(param);
        }
        case "isFav": {
            return checkFavorites(param.resId, param.userId);
        }
    }
};

async function addFavorites(param) {
    let now = new Date();
    let year = now.getFullYear(); // 获取年份
    let month = now.getMonth() + 1; // 获取月份（返回值范围：0-11，需要加1）
    let day = now.getDate(); // 获取日期（返回值范围：1-31）
    let dateString = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;

    return await db.collection("aiExtra_user_favorites").add({
        userId: param.userId,
        resId: param.resId,
        favoriteTime: dateString
    });
};

async function checkFavorites(resId, userId) {
    return await db.collection("aiExtra_user_favorites").where({
        resId,
        userId
    }).count();
};

async function getFavoritesResList(currentPage, userId) {
    const result = await db.collection('aiExtra_user_favorites').aggregate()
        .lookup({
            from: 'aiExtra_resources',
            foreignField: '_id',
            localField: 'resId',
            as: 'res',
        })
        .match({
            userId: dbCmd.eq(userId)
        })
        .project({
            "favoriteTime": true,
            "_id": false,
            'res._id': true,
            'res.title': true,
            'res.headPic': true,
            'res.likeCount': true,
            'res.label': true
        })
        .sort({
            favoriteTime: -1
        }).limit(10).skip(currentPage * 10).end();

    return result.data.map(item => {
        let newResItem = {
            _id: item.res[0]._id,
            title: item.res[0].title,
            headPic: item.res[0].headPic,
            label: item.res[0].label,
            likeCount: item.res[0].likeCount
        }
        return {
            _id: item._id,
            favoriteTime: item.favoriteTime,
            ...newResItem
        }
    });
}
